package com.kovalko.pages;

import com.kovalko.utils.Log4Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.testng.Assert;

/**
 * Created by 4uvak on 06.07.2014.
 */
public class SearchResultsPage extends BasePage {
    private static final String SEARCH_PAGE_URL = "http://rozetka.com.ua";
    private static final String SEARCH_FIELD_CLASS = "text";
    private static final String SEARCH_BUTTON_PATH = "//*[@id=\"body-header\"]/div[2]/div/div/div/div[2]/form/div[1]/span/button";
    private static final String FOUND_PRODUCT_PATH = "//*[@id=\"head_banner_container\"]/div[3]/div/div[1]/div/div/div[3]/div/div[2]/div[1]/a";
    private static final String PRODUCT_CODE_PATH = "//*[@id=\"head_banner_container\"]/div[3]/div/div[1]/div/div[1]/header/div[2]";


    public SearchResultsPage(WebDriver driver) {
        super(driver,SEARCH_PAGE_URL);
    }

    public String getProductCodeByProductName(String productName) throws InterruptedException {
        WebElement search = driver.findElement(By.name(SEARCH_FIELD_CLASS));
        search.click();
        Thread.sleep(100);

        search.sendKeys(productName);
        driver.findElement(By.xpath(SEARCH_BUTTON_PATH)).click();

        String foundProductName = driver.findElement(By.xpath(FOUND_PRODUCT_PATH)).getText();
        Assert.assertTrue(foundProductName.contains(productName), "Required good not found. actual:" + foundProductName + ". expected:" + productName);

        driver.findElement(By.xpath(FOUND_PRODUCT_PATH)).click();
        String productCode = driver.findElement(By.xpath(PRODUCT_CODE_PATH)).getText();
        if (productCode.startsWith("Код ")) {
            productCode = productCode.substring(4);
        }
        Log4Test.info(productName +" has code " + productCode);
        return productCode;
    }
}
